﻿using AnlianCommon.Common.Domains.BeginningManagement;
using AnlianCommon.Common.Domains.OrganizationalUnits;
using AnlianCommon.Common.Domains.UserPermissions;
using AnlianCommon.Common.DTO;
using AnlianCommon.Common.Infrastructure.IRepository;
using AnlianCommon.Enum;
using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AnlianCommon.API.Commands.Startofseasons
{
    public class StartofseasonSearchZeroHander : IRequestHandler<StartofseasonSearchZeroCommand, ResultPage<Startofseason>>
    {
        private readonly IBaseRepository<Startofseason> _startofseasonRepository;
        private readonly IMapper _mapper;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="startofseasonRepository"></param>
        /// <param name="mapper"></param>
        public StartofseasonSearchZeroHander(IBaseRepository<Startofseason> startofseasonRepository, IMapper mapper)
        {
            _startofseasonRepository = startofseasonRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 公羊期初显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Startofseason>> Handle(StartofseasonSearchZeroCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Startofseason> { Code = (int)CommonErrorCode.Search, TotalCount = 0, PagedCount = 0 };
            try
            {
                var startofseason = await (await _startofseasonRepository.GetAll()).Where(x => x.SeasonType == 0).ToListAsync();
                if (!string.IsNullOrEmpty(request.Auricle))
                {
                    startofseason = startofseason.Where(x => x.Auricle == request.Auricle).ToList();
                }
                result.TotalCount = startofseason.Count;
                result.PagedCount = (int)Math.Ceiling((result.TotalCount * 1.0) / request.PageSize);
                startofseason = startofseason.OrderByDescending(c => c.SeasonId).Skip((request.PageIndex - 1) * request.PageSize).Take(request.PageSize).ToList();
                result.Data = startofseason;
            }
            catch (Exception)
            {

                throw;
            }
            return result;
        }
    }
}
